package com.atguigu.myjuc.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket{
    //资源类
    private int P = 50;

    //synchronized锁

    /*public synchronized void sale(){
        if (P>0){
            System.out.println(Thread.currentThread().getName()+"卖出第："+(P--)+"剩余票数："+(P));
        }
    }*/
            // ReentrantLock 多态 Lock
    private final Lock lock = new ReentrantLock(true); // ReentrantLock = 可重入锁 默认悲观锁 默认公平锁

    public void sale(){
        /*lock.lock();
        try {
            if (P>0){
                System.out.println(Thread.currentThread().getName()+"卖出第："+(P--)+"剩余票数："+(P));
                //Thread.yield();  //让出 CPU
                Thread.sleep(10); // 增加延迟，减少锁竞争频率
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }*/
        lock.lock();
        try {
            if (P>0){
                System.out.println(Thread.currentThread().getName()+"卖出第："+(P--)+"剩余票数："+(P));
            }
        } finally {
            lock.unlock();
        }
    }

    }

public class SaleTicketDemo {
    /*
    需求：
    50张票分别由三个售票员出售
    * 小口诀：
    * 1.高内聚低耦合前提下  线程  操作  资源类
    * */
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        //V1

        /*new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 1; i <= 50; i++) {
                            ticket.sale();
                        }
                    }
                }, "A").start();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 1; i <= 50; i++) {
                            ticket.sale();
                        }
                    }
                }, "B").start();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 1; i <= 50; i++) {
                            ticket.sale();
                        }
                    }
                }, "C").start();*/


        //V2  拉姆达形式

        new Thread(() ->{for (int i = 1; i <= 50; i++) ticket.sale();},"A").start();
        new Thread(()-> {for (int i = 1; i <= 50; i++) ticket.sale();},"B").start();
        new Thread(() ->{for (int i = 1; i <= 50; i++) ticket.sale();},"C").start();

    }
}
